const path = require('path')
const fs = require('fs')
module.exports = class TestNow{

    /**
     * 
     * @param {*} sourcePath 
     */
    getJestSource(sourcePath = path.resolve('./')){
        console.log(sourcePath);
        const testPath = `${sourcePath}/__test__`
        if(!fs.existsSync(testPath)){
            fs.mkdirSync(testPath)
        }
        // 遍历代码文件
        let list = fs.readdirSync(sourcePath)
        console.log(list);
        list
            // 添加完整路径
            .map(v => `${sourcePath}/${v}`)
            // 过滤文件
            .filter(v => fs.statSync(v).isFile())
            // 
            .filter(v => v.indexOf('.spec') === -1)
            .map(v => this.getTestFile(v))
    }

    /**
     * 
     * @param {*} fileName 
     */
    getTestFile(fileName){
        console.log('fileName:', fileName);
        const testFileName = this.getTestFileName(fileName)

        // 判断此文件是否存在
        if(fs.existsSync(testFileName)) {
            console.log('测试代码已生成：', testFileName);
            return
        }

        const mod = require(fileName)

        let source
        if(typeof mod === 'object'){
            source = Object.keys(mod)
                .map(v => this.getTestSource(v, path.basename(fileName), true))
                .join('\n')
        } else if(typeof mod === 'function'){
            const baseName = path.basename(fileName)
            source = this.getTestSource(baseName.replace('.js', ''), baseName)

        }
        fs.writeFileSync(testFileName, source)

    }

    /**
     * 
     * @param {*} methodName 
     * @param {*} classFile 
     * @param {*} isClass 
     * @returns 
     */
    getTestSource(methodName, classFile, isClass = false){
        console.log('getTestSource:', methodName, classFile, isClass);
        return `
            test('${'TEST_' + methodName}：', ()=>{
                const ${ isClass ? '{' + methodName + '}' : methodName } = require('../${ classFile }')
                const ret = ${methodName}()
                // expect(res)
                //  .toBe('test return')
            })
        `
    }
    /**
     * 生成测试文件名
     * @param {*} filename 代码文件名
     * @returns 
     */
    getTestFileName(filename){
        // 目录的名称
        const dirName = path.dirname(filename)
        // 文件名
        const baseName = path.basename(filename)
        // 文件类型
        const extName = path.extname(filename)
        // 生成的文件名
        const testName = baseName.replace(extName, `.spec${extName}`)

        return path.format({
            root: dirName + '/__test__/',
            base: testName
        })
    }
}